package com.gary.shiro.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author peng_rui
 * @date 2022/4/19
 */
@Component
public class RedisLock implements ILock{

    private RedisTemplate<String, Object> redisTemplate;
    private String name;
    private static final String PREFIX = "lock:";

    public RedisLock() {}

    public RedisLock(String name, RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    @Override
    public Boolean tryLock(Long timeoutSec) {
        String uuid = UUID.randomUUID().toString();
        //尝试加锁
        return redisTemplate.opsForValue().setIfAbsent(PREFIX + name, uuid, timeoutSec, TimeUnit.SECONDS);
    }

    @Override
    public Boolean unLock() {
//        redisTemplate.execute()
        return redisTemplate.delete(PREFIX + name);
    }
}
